package com.spark.rectify

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.spark.colliery.common.ext.gone
import com.spark.common.Api
import com.spark.common.BaseFragment
import com.spark.common.ext.*
import com.spark.common.helper.Picker
import com.spark.common.model.ImgUploadResultModel
import kotlinx.android.synthetic.main.frag_rect_info.*

/**
 * 纠违信息
 */
class RectInfoFragment : BaseFragment() {
    private lateinit var unSafeActionAdapter: UnSafeActionAdapter
    private lateinit var uploadImgAdapter: UploadImgAdapter

    private val actions = mutableListOf<UnSafeActionModel>()
    private val localImg = mutableListOf<String>()
    private val cloudImg = mutableListOf<String>()
    private lateinit var plusImgPath: String

    companion object {
        const val reqStdUnsafeActionList = 0x3333

        fun newInstance(): RectInfoFragment {
            val target = RectInfoFragment()
            val args = Bundle()

            target.arguments = args
            return target
        }
    }

    private val actDataObserver = object : RecyclerView.AdapterDataObserver() {
        override fun onChanged() {
            super.onChanged()
            val datasize = unSafeActionAdapter.data.size
            ll_empty.gone(datasize != 0)
            ll_full.gone(datasize == 0)
        }
    }
    private val imgDataObserver = object : RecyclerView.AdapterDataObserver() {
        override fun onChanged() {
            super.onChanged()
            val dataIsEmpty = uploadImgAdapter.data.isEmpty()
            ll_empty.gone(!dataIsEmpty)
            ll_full.gone(dataIsEmpty)
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_rect_info
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        ll_empty.gone(actions.isNotEmpty())
        ll_full.gone(actions.isEmpty())
        // 不安全行为
        recy_unsafe_actions.apply {
            unSafeActionAdapter = UnSafeActionAdapter(R.layout.item_unsafe_action).apply {
                setOnItemChildClickListener { adapter, view, position ->
                    if (view.id == R.id.iv_del) {
                        remove(position)
                        actions.removeAt(position)
                    }
                }
                setOnItemClickListener { adapter, view, position ->

                }

                registerAdapterDataObserver(actDataObserver)
            }
            adapter = unSafeActionAdapter
            layoutManager = object : LinearLayoutManager(context) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
        }
        // 责任人
        iv_entry1.setOnClickListener {
            activity?.apply { UnsafeActionRespManActivity.actionStartForBack(this, 0x121) }
        }
        // 允许申诉
        allow_reject.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                success("允许申诉")
            } else {
                error("禁止申诉")
            }
        }
        // 添加不安全行为
        iv_entry4.setOnClickListener {
            activity?.apply { StdUnsafeActionListActivity.actionStartBack(this, reqStdUnsafeActionList) }
        }
        iv_entry5.setOnClickListener {
            activity?.apply { StdUnsafeActionListActivity.actionStartBack(this, reqStdUnsafeActionList) }
        }
        // 行为描述
        et_act_desc
        // 不安全行为-图片
        plusImgPath = context.relAbsPath(R.drawable.img_plus_add)
        if (!localImg.contains(plusImgPath)) localImg.add(plusImgPath)
        recy_source_imgs.apply {
            uploadImgAdapter = UploadImgAdapter(R.layout.item_img_upload, true).apply {
                if (canEdit && !data.contains(plusImgPath)) addData(plusImgPath)
                setOnItemClickListener { adapter, view, position ->
                    val dataSize = adapter.data.size
                    val item = adapter.data[position]
                    if (item == plusImgPath) imgClick(position, dataSize)
                    else success("点击图片【$position】")
                }
                setOnItemChildClickListener { adapter, view, position ->
                    val imgPath = uploadImgAdapter.data[position]
                    if (localImg.contains(imgPath)) localImg.remove(imgPath)
                    if (position in 0 until cloudImg.size - 1) {
                        cloudImg.removeAt(position)
                        cloudImg.removeAt(position)
                    }
                    if (localImg.size < 4 && !localImg.contains(plusImgPath)) localImg.add(plusImgPath)
                    uploadImgAdapter.replaceData(localImg)
                }
                // registerAdapterDataObserver(imgDataObserver)
            }
            adapter = uploadImgAdapter
            layoutManager = context.glm(4)
        }
    }

    private fun imgClick(position: Int, totalSize: Int) {
        if (position == totalSize - 1) {
            activity?.apply {
                Picker(this).show {
                    uploadImg(it)
                }
            }
        } else {
            success("点击图片【$position】")
        }
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        val gson = Gson()

        when (requestCode) {
            0x121 -> {
                if (resultCode == 0x221) {
                    data?.apply {
                        val type = object : TypeToken<LevelThree>() {}.type
                        gson.fromJson<MutableList<LevelThree>>(getString("results"), type)?.apply {
                            LogUtils.e(this)
                        }
                    }
                }
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun uploadImg(imgPath: String) {
        Api.upload(imgPath)
                .subscribe(
                        {
                            Gson().fromJson(it, ImgUploadResultModel::class.java)?.apply {
                                if (code == "200") {
                                    if (resultMaps.isNotEmpty()) {
                                        resultMaps[0].apply {
                                            if (!cloudImg.contains(this.url)) {
                                                cloudImg.add(this.url)
                                                //loudFileId.add(this.fileId.toString())
                                            }
                                            if (!localImg.contains(imgPath)) localImg.add(0, imgPath)
                                            if (localImg.size >= 5) localImg.removeAt(4)
                                            uploadImgAdapter.replaceData(localImg)
                                        }
                                    }
                                }
                            }
                        },
                        {
                            hideLoader()
                            it.printStackTrace()
                            report(it)
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("上传中...")
                        }
                )
    }

    override fun onDestroy() {
        super.onDestroy()
        unSafeActionAdapter.unregisterAdapterDataObserver(actDataObserver)
//        uploadImgAdapter.unregisterAdapterDataObserver(imgDataObserver)
    }
}

class UnSafeActionAdapter(layoutRes: Int) : BaseQuickAdapter<UnSafeActionModel, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: UnSafeActionModel?) {
        if (item == null) return
        helper?.apply {
            setText(R.id.tv_act_name, item.actName)
            setText(R.id.tv_act_desc, item.actDesc)
            setText(R.id.tv_time, item.time)
            setText(R.id.tv_level, item.level)
            getView<ImageView>(R.id.iv_del).setOnClickListener {
                onItemChildClickListener?.onItemChildClick(this@UnSafeActionAdapter, it, adapterPosition)
            }
        }
    }

}

class UploadImgAdapter(layoutRes: Int, var canEdit: Boolean) : BaseQuickAdapter<String, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: String?) {
        if (item == null) return
        helper?.apply {
            val ivImg = getView<ImageView>(R.id.iv_danger_img)
            if (item == mContext.relAbsPath(R.drawable.img_plus_add)) {
                ivImg.setImageResource(R.drawable.img_plus_add)
            } else {
                ivImg.local(item)
            }
            getView<ImageView>(R.id.iv_delete).apply {
                if (canEdit) {
                    gone(mContext.relAbsPath(R.drawable.img_plus_add) == item)
                } else {
                    gone(true)
                }
                setOnClickListener {
                    onItemChildClickListener?.onItemChildClick(this@UploadImgAdapter, it, adapterPosition)
                }
            }
        }
    }

}

data class UnSafeActionModel(
        var actName: String = "",
        var actDesc: String = "",
        var time: String = "",
        var level: String = ""
)